from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.image import SkuImageView, SKUSerialize
from meiduo_admin.utils import PageNum


class ImagesShowView(ModelViewSet):
    serializer_class = SkuImageView
    queryset = SKUImage.objects.all()
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # client = Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')

        data = request.FILES.get('image')
        res = client.upload_by_buffer(data.read())
        if res['Status'] != 'Upload successed.':
            return Response(status=403)

        image_url = res['Remote file_id']
        sku_id = request.data.get('sku')
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)

        return Response({
            'id': img.id,
            'sku': sku_id,
            'image': img.image.url
        },
            status=201)

    def destroy(self, request, *args, **kwargs):
        sku_id = kwargs['pk']
        good = SKUImage.objects.get(id=sku_id)
        good.delete()

        return Response({
            'msg': 'ok',
        },
            status=201)


class AddSimpleView(APIView):

    def get(self, request):
        data = SKU.objects.all()
        # good_list = []
        # for good in goods:
        #     good_list.append({
        #         'id': good.id,
        #         'name': good.name
        #     })

        ser = SKUSerialize(data, many=True)
        return Response(ser.data)
